# -*- coding:utf-8 -*-

import os
import shutil
import time
import traceback

from PIL import Image, ImageDraw, ImageFont
from git import Repo

max_file_size = 500000

class ImageCompress:
    def __init__(self):
        pass

    @staticmethod
    def get_image_file_list(scan_path, exclude=""):
        result = []
        for parent, _, file_names in os.walk(scan_path):
            if exclude and parent.startswith(exclude):
                continue
            for file_name in file_names:
                file_ext = os.path.splitext(file_name)[-1].lower()
                if file_ext in [".jpg", ".jpeg", ".png", ".bmp"]:
                    result.append(os.path.join(parent, file_name))
        return result

    @staticmethod
    def handle_images(image_path, backup_path):
        # 获取图片列表
        image_list = ImageCompress.get_image_file_list(image_path, backup_path)

        # 获取备份列表
        backup_list = ImageCompress.get_image_file_list(backup_path)

        compressed_image_list = []
        for file_full_name in image_list:
            if os.path.getsize(file_full_name) <= max_file_size:
                continue
            file_related_name = file_full_name[len(image_path) + 1:]
            backup_full_name = ImageCompress.gen_back_path(backup_path,
                                                           file_related_name)
            if backup_full_name not in backup_list:
                print("back image: {}".format(file_full_name))
                # 备份原始图片
                ImageCompress.safe_mkdir(os.path.split(backup_full_name)[0])
                shutil.copyfile(file_full_name, backup_full_name)
            try:
                # 压缩
                ImageCompress.compress(file_full_name)
            except Exception as e:
                print("{}".format(e))
                print(traceback.format_exc())
                shutil.copyfile(backup_full_name, file_full_name)
                os.remove(backup_full_name)

            compressed_image_list.append(file_related_name)

        print("compressed list: {}".format(compressed_image_list))
        return compressed_image_list

    @staticmethod
    def gen_back_path(backup_path, relative_path):
        #split_path = os.path.splitext(relative_path)
        backup_full_name = os.path.join(backup_path, relative_path)
        return backup_full_name

    @staticmethod
    def safe_mkdir(target_dir):
        if not os.path.exists(target_dir):
            os.makedirs(target_dir)

    @staticmethod
    def compress(image_file_name):
        file_size = os.path.getsize(image_file_name)
        qual = 95
        step = 5
        while file_size > max_file_size:
            qual -= step
            if qual - step < 0:
                print("compress file faled:{}".format(image_file_name))
                break

            img = Image.open(image_file_name)
            #max_width = 1280
            #if img.size[0] > max_width:
            #    img = img.resize((max_width, int(float(max_width) / (img.size[0]) * img.size[1])))
            if img.mode != "RGB":
                img = img.convert('RGB')
            img.save(image_file_name, "JPEG", quality=qual)
            file_size = os.path.getsize(image_file_name)

if __name__ == "__main__":
    repo_pic = '/Users/ferrisyu/source/codingxx_pictures/static_res'
    # repo = Repo(repo_pic)
    # git = repo.git
    # print(git.reset('--hard'))
    # print(git.clean('-xdf'))
    # print(git.pull())

    handler = ImageCompress()
    result_list = handler.handle_images(repo_pic,
                                        repo_pic + r"/backup")

    repo_pic = '/Users/ferrisyu/source/codingxx_pictures/marked_res'
    handler = ImageCompress()
    result_list = handler.handle_images(repo_pic,
                                        repo_pic + r"/backup")

    #with open('/tmp/marked_list.txt', 'w') as f:
    #    for file_name in marked_list:
    #        f.write('https://purge.jsdelivr.net/gh/yu-fei/pictures@master/marked/' + file_name + "\n")

    # if repo.is_dirty() or len(repo.untracked_files) > 0:
    #     print(git.add('--all', '.'))
    #     print(git.commit('-m', "add mark to image " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
